package gvo.amazon;

import gvo.importWindow.InternetImport;
import gvo.sql.SQLWizard;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.jdesktop.swingworker.SwingWorker;

import com.amazonaws.a2s.AmazonA2SClient;
import com.amazonaws.a2s.AmazonA2SException;
import com.amazonaws.a2s.AmazonA2SLocale;
import com.amazonaws.a2s.model.Item;
import com.amazonaws.a2s.model.ItemAttributes;
import com.amazonaws.a2s.model.ItemSearchRequest;
import com.amazonaws.a2s.model.ItemSearchResponse;
import com.amazonaws.a2s.model.Items;

public class AmazonSearch {
	private static String accessKeyId = "0HWNZX10PJY6Q2C6NFR2";
	private static String associateTag = "-01e-20";
	private static String searchIndex = "Books";
	/*
	Books
	ForeignBooks
	Music
	DVD
	*/
	private static String searchOrder = "titlerank";
/*
 * SearchIndex: Books
* 	Value		Description
	salesrank	Bestselling
	reviewrank	Average customer review: high to low
	pricerank	Price: low to high
	inverse-pricerank	Price: high to low
	titlerank	Alphabetical: A to Z
	-titlerank	Alphabetical: Z to A
 */
	
	public static void searchAmazon(String keyword, InternetImport intImp, SQLWizard sqlTool) {

		AmazonSearchResult asr = new AmazonSearchResult();
		asr.service = new AmazonA2SClient(accessKeyId, associateTag, AmazonA2SLocale.DE);
		asr.query = keyword;
		AmazonResultPage arp = new AmazonResultPage();
		arp.request = new ItemSearchRequest();
		arp.request.setSearchIndex(searchIndex);
		arp.request.setSort(searchOrder);
		/*
		SearchIndex: Books

		In an ItemSearch request, when the SearchIndex parameter equals "Books", only the following parameters can be used in the request.
		Author
		BrowseNode
		Condition
		ItemPage
		Keywords
		MaximumPrice
		MerchantId
		MinimumPrice
		Power
		Publisher
		Sort
		Title
	*/
		arp.request.setKeywords(keyword);
		
		java.util.List<String> responseGroups = new ArrayList<String>();
		responseGroups.add("Medium");
		arp.request.setResponseGroup(responseGroups);
		asr.query = keyword;
		arp.snr = 0;
		asr.pages.add(arp);
		getPage(0, asr, arp, intImp, sqlTool);

	}

	// intern 0,1, ....
	// amazon 1,2, ... also snr++
	public static boolean loadPage(int snr, AmazonSearchResult asr, InternetImport intImp, SQLWizard sqlTool) {
		if (asr.pages.size() == 0) {
			return false;
		}
		AmazonResultPage arp = asr.getAmazonResultPage(snr);
		if (arp == null) {
			arp = new AmazonResultPage();
			arp.snr = snr;
			arp.request = new ItemSearchRequest();
			arp.request.setSearchIndex(searchIndex);
			arp.request.setKeywords(asr.query);
			arp.request.setItemPage(new BigInteger(String.valueOf(snr + 1)));
			java.util.List<String> responseGroups = new ArrayList<String>();
			responseGroups.add("Medium");
			arp.request.setResponseGroup(responseGroups);
			asr.pages.add(arp);
		}

		if (!arp.isFilled) {
			getPage(snr, asr, arp, intImp, sqlTool);
		} else {
			intImp.showAmazonResultPage(arp, asr.totalPages, snr, asr.totalResults);
		}

		return true;
	}

	private static void getPage(final int snr, final AmazonSearchResult asr,
			final AmazonResultPage arp, final InternetImport intImp, final SQLWizard sqlTool) {

		if (intImp.aWorker != null) {
			System.out.println("interrupt!");
			intImp.aWorker.cancel(true);
			intImp.aWorker = null;
		}
		intImp.aWorker = new SwingWorker<ItemSearchResponse, Void>() {

			@Override
			protected ItemSearchResponse doInBackground() throws Exception {
				//System.out.println("Thread start");
				ItemSearchResponse isr = null;
				try {
					isr = asr.service.itemSearch(arp.request);
				} catch (AmazonA2SException e){
					System.out.println("Nix gefunden!");
					//e.printStackTrace();
				}
				//System.out.println("Thread ende");
				return isr;
			}

			public void done() {
				if (this.isCancelled()) {
					//System.out.println("Thread ist cancelled!");
					return;
				}
				try {
					intImp.searchQ = asr;
					arp.response = get();
					if(arp.response==null){
						intImp.statusRI.setText("Kein passendes Buch gefunden!");
						return;
					}
					java.util.List<Items> itemssList = arp.response.getItems();
					for (Items items : itemssList) {
						if (items.isSetTotalPages()) {
							asr.totalPages = items.getTotalPages().intValue();
						}
						if (items.isSetTotalResults()) {
							asr.totalResults = items.getTotalResults().intValue();
						}

						java.util.List<Item> itemsList = items.getItem();
						getPagesResults(itemsList, arp, sqlTool);
						intImp.showAmazonResultPage(arp, asr.totalPages, snr, asr.totalResults);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}

			}

		};
		
		intImp.aWorker.execute();
		

	}

	private static void getPagesResults(java.util.List<Item> itemsList, AmazonResultPage arp, SQLWizard sqlTool) {
		AmazonEntry tmp;
		for (Item item : itemsList) {
			tmp = new AmazonEntry();
			if (item.isSetASIN()) {
				tmp.asin = item.getASIN();
			}
			if (item.isSetLargeImage()) {
				tmp.largeImageURL = item.getLargeImage().getURL();
				//System.out.println(tmp.largeImageURL);
			}
			if (item.isSetItemAttributes()) {
				ItemAttributes itemAttributes = item.getItemAttributes();

				java.util.List<String> authorsList = itemAttributes.getAuthor();
				for (String author : authorsList) {
					tmp.autoren.add(author);
				}

				if (itemAttributes.isSetISBN()) {
					tmp.isbn = itemAttributes.getISBN();
				}

				if (itemAttributes.isSetEdition()) {
					tmp.edition = itemAttributes.getEdition();
				}

				if (itemAttributes.isSetBinding()) {
					tmp.binding = itemAttributes.getBinding();
				}

				if (itemAttributes.isSetPublisher()) {
					tmp.publisher = itemAttributes.getPublisher();
				}

				if (itemAttributes.isSetNumberOfPages()) {
					tmp.numberOfPages = itemAttributes.getNumberOfPages().intValue();
				}

				if (itemAttributes.isSetPublicationDate()) {
					tmp.publicationDate = itemAttributes.getPublicationDate();
				}

				if (itemAttributes.isSetTitle()) {
					tmp.titel = itemAttributes.getTitle();
				}

			}
			tmp.fillGVOall(sqlTool);
			arp.entries.add(tmp);
		}
		arp.isFilled = true;
	}
}
